import { useEffect, useRef, useState } from 'react'
import { Button, Table, Modal, Form, Input, FormInstance, Popconfirm } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import Upload from '../../components/Upload'
import useMessage from '../../utils/message'

import { add, addChildren, deleteById, deleteChildrenById, get, getChildren, update, updateChildren } from '../../api/classification'
import getEnv from '../../utils/env'

import './classification.scss'

function Classification() {
  const message = useMessage()
  const addForm = useRef<FormInstance>(null)

  const addChilrenForm = useRef<FormInstance>(null)

  const [currentFile, setCurrentFile] = useState<File | null>()

  const [currentChildrenFile, setCurrentChildrenFile] = useState<File | null>()

  const [fileList, setFileList] = useState<FileList[]>([])

  const [fileChildrenList, setFileChildrenList] = useState<FileList[]>([])

  const [table, setTable] = useState<Classification[]>([])

  const [tableChildren, setTableChildren] = useState<ClassificationChildren[]>([])

  const [isModalOpen, setIsModalOpen] = useState(false)

  const [isModalUpdateOpen, setIsModalUpdateOpen] = useState(false)

  const [modalOpenTitle, setModalOpenTitle] = useState('')

  const [isModalChildrenOpen, setIsModalChildrenOpen] = useState(false)

  const [isModalChildrenUpdateOpen, setIsModalChildrenUpdateOpen] = useState(false)

  const [modalChildrenTitle, setModalChildrenTitle] = useState('')

  const [listModal, setListModal] = useState(false)

  const [currentClassification, setCurrentClassification] = useState<Classification | null>(null)

  const [currentChildren, setCurrentChildren] = useState<ClassificationChildren | null>(null)

  function handleModal() {
    setCurrentClassification(null)
    setModalOpenTitle('新增分类')
    setCurrentFile(null)
    setFileList([])
    setIsModalOpen(true)
  }

  function handleConfirm() {
    addForm.current?.validateFields().then((values) => {
      if (isModalUpdateOpen) {
        update(
          {
            name: values.name,
            description: '',
            img: fileList.length ? fileList[0].url : ''
          },
          currentClassification!.id
        ).then(({ msg }) => {
          setCurrentClassification(null)
          setIsModalUpdateOpen(false)
          message.success(msg)
          getData()
        })
      } else {
        add({
          name: values.name,
          description: '',
          img: fileList.length ? fileList[0].url : ''
        }).then(({ msg }) => {
          setIsModalOpen(false)
          message.success(msg)
          getData()
        })
      }
    })
  }

  function handleConfirmDelete(id: number) {
    deleteById(id).then(({ msg }) => {
      message.success(msg)
      getData()
    })
  }

  function handleList(item: Classification) {
    setCurrentClassification({ ...item })
    setListModal(true)
    getChildren(item.id).then(({ data }) => {
      setTableChildren([...data!.classificationChildren])
    })
  }

  function handleChildrenModal() {
    setCurrentChildren(null)
    setModalChildrenTitle('新增')
    setCurrentChildrenFile(null)
    setFileChildrenList([])
    setIsModalChildrenOpen(true)
  }

  function handleChildrenConfirm() {
    addChilrenForm.current?.validateFields().then((values) => {
      if (isModalChildrenUpdateOpen) {
        updateChildren(
          {
            name: values.name,
            description: '',
            img: fileChildrenList.length ? fileChildrenList[0].url : '',
            classificationId: currentClassification?.id
          },
          currentChildren!.id
        ).then(({ msg }) => {
          setCurrentChildren(null)
          setIsModalChildrenUpdateOpen(false)
          message.success(msg)
          handleList(currentClassification!)
        })
      } else {
        addChildren({
          name: values.name,
          img: fileChildrenList.length ? fileChildrenList[0].url : '',
          classificationId: currentClassification?.id
        }).then(({ msg }) => {
          setIsModalChildrenOpen(false)
          message.success(msg)
          handleList(currentClassification!)
        })
      }
    })
  }

  function handleChildrenConfirmDelete(id: number) {
    deleteChildrenById(id).then(({ msg }) => {
      message.success(msg)
      handleList(currentClassification!)
    })
  }

  function handleUpdate(item: Classification) {
    setModalOpenTitle('编辑分类')

    if (item.img) {
      setCurrentFile({
        type: 'image',
        name: item.img,
        size: 0,
        slice: () => new Blob()
      } as File)
      setFileList([{ url: item.img } as FileList])
    } else {
      setCurrentFile(null)
      setFileList([])
    }
    setCurrentClassification(item)
    setIsModalUpdateOpen(true)
  }

  function handleChildrenUpdate(item: ClassificationChildren) {
    setModalChildrenTitle('编辑')
    if (item.img) {
      setCurrentChildrenFile({
        type: 'image',
        name: item.img,
        size: 0,
        slice: () => new Blob()
      } as File)
      setFileChildrenList([{ url: item.img } as FileList])
    } else {
      setCurrentChildrenFile(null)
      setFileChildrenList([])
    }

    setCurrentChildren(item)
    setIsModalChildrenUpdateOpen(true)
  }

  const columns: ColumnsType<Classification> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '图片',
      dataIndex: 'img',
      key: 'img',
      render(_: unknown, item: Classification) {
        return <img className="table-img" src={getEnv('img_url') + item.img} alt="" />
      }
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description'
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      render(_: unknown, item: Classification) {
        return (
          <div className="table-btn">
            <Button
              type="link"
              onClick={() => {
                handleList(item)
              }}
            >
              详情
            </Button>
            <Button
              type="link"
              onClick={() => {
                handleUpdate(item)
              }}
            >
              编辑
            </Button>
            <Popconfirm title="删除确认" onConfirm={() => handleConfirmDelete(item.id)} onCancel={() => {}} okText="确认" cancelText="取消">
              <Button type="link" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        )
      }
    }
  ]

  const columnsChildren: ColumnsType<ClassificationChildren> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '图片',
      dataIndex: 'img',
      key: 'img',
      render(_: unknown, item: ClassificationChildren) {
        return <img className="table-img" src={getEnv('img_url') + item.img} alt="" />
      }
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description'
    },
    {
      title: '操作',
      dataIndex: 'handle',
      key: 'handle',
      render(_: unknown, item: ClassificationChildren) {
        return (
          <div className="table-btn">
            <Button
              type="link"
              onClick={() => {
                handleChildrenUpdate(item)
              }}
            >
              编辑
            </Button>
            <Popconfirm title="删除确认" onConfirm={() => handleChildrenConfirmDelete(item.id)} onCancel={() => {}} okText="确认" cancelText="取消">
              <Button type="link" danger>
                删除
              </Button>
            </Popconfirm>
          </div>
        )
      }
    }
  ]

  function getData() {
    get().then(({ data }) => {
      setTable([...data!])
    })
  }

  useEffect(() => {
    getData()

    setTableChildren([])
  }, [])

  return (
    <div className="classification">
      <div className="classification-header">
        <Button type="primary" onClick={handleModal}>
          新增
        </Button>
      </div>
      <Table dataSource={table} columns={columns} scroll={{ y: 500 }} rowKey="id" pagination={false}></Table>

      {isModalOpen || isModalUpdateOpen ? (
        <Modal
          title={modalOpenTitle}
          open={true}
          onCancel={() => {
            setIsModalUpdateOpen(false)
            setIsModalOpen(false)
          }}
          onOk={handleConfirm}
        >
          <div className="classification-add">
            <Form ref={addForm} labelCol={{ span: 5 }} initialValues={currentClassification as never}>
              <Form.Item label="分类名称" name="name" rules={[{ required: true, message: '请输入分类名称' }]}>
                <Input placeholder="请输入分类名称" />
              </Form.Item>
              <Form.Item
                label="分类图片"
                name="img"
                rules={[
                  {
                    required: true,
                    validator: () => {
                      if (!currentFile || !currentFile.type.includes('image')) {
                        return Promise.reject(new Error('请上传图片文件'))
                      }
                      return Promise.resolve()
                    }
                  }
                ]}
              >
                <Upload
                  beforeUpload={(file: File) => {
                    setCurrentFile(file)
                    addForm.current?.validateFields(['img'])
                    return file.type.includes('image')
                  }}
                  maxLength={1}
                  defaultFileList={fileList}
                  change={(fileList: FileList[]) => {
                    if (!fileList.length) setCurrentFile(null)
                    setFileList([...fileList])
                  }}
                />
              </Form.Item>
            </Form>
          </div>
        </Modal>
      ) : (
        ''
      )}

      {listModal ? (
        <Modal
          footer={null}
          width={1200}
          title={currentClassification?.name + '列表'}
          open={true}
          onCancel={() => {
            setListModal(false)
          }}
        >
          <div className="classification-header">
            <Button type="primary" onClick={handleChildrenModal}>
              新增
            </Button>
          </div>
          <Table dataSource={tableChildren} columns={columnsChildren} scroll={{ y: 500 }} rowKey="id" pagination={false}></Table>
        </Modal>
      ) : (
        ''
      )}

      {isModalChildrenOpen || isModalChildrenUpdateOpen ? (
        <Modal
          title={modalChildrenTitle + currentClassification?.name + '分类'}
          open={true}
          onCancel={() => {
            setIsModalChildrenUpdateOpen(false)
            setIsModalChildrenOpen(false)
          }}
          onOk={handleChildrenConfirm}
        >
          <div className="classification-add">
            <Form ref={addChilrenForm} labelCol={{ span: 5 }} initialValues={currentChildren as never}>
              <Form.Item label="分类名称" name="name" rules={[{ required: true, message: '请输入分类名称' }]}>
                <Input placeholder="请输入分类名称" />
              </Form.Item>
              <Form.Item
                label="分类图片"
                name="img"
                rules={[
                  {
                    required: true,
                    validator: () => {
                      if (!currentChildrenFile || !currentChildrenFile.type.includes('image')) {
                        return Promise.reject(new Error('请上传图片文件'))
                      }
                      return Promise.resolve()
                    }
                  }
                ]}
              >
                <Upload
                  beforeUpload={(file: File) => {
                    setCurrentChildrenFile(file)
                    addChilrenForm.current?.validateFields(['img'])
                    return file.type.includes('image')
                  }}
                  maxLength={1}
                  defaultFileList={fileChildrenList}
                  change={(fileList: FileList[]) => {
                    if (!fileList.length) setCurrentChildrenFile(null)
                    setFileChildrenList([...fileList])
                  }}
                />
              </Form.Item>
            </Form>
          </div>
        </Modal>
      ) : (
        ''
      )}
    </div>
  )
}

export default Classification
